package controller

import (
	"net/http"

	"gitee.com/jabberwocky238/proj-backend/model"
	"gitee.com/jabberwocky238/proj-backend/service"
	"github.com/gin-gonic/gin"
)

// func MusicUpload(c *gin.Context) {
// 	// 获取formdata
// 	uuid := c.PostForm("uuid")
// 	title := c.PostForm("title")
// 	thumbnail := c.PostForm("thumbnail")
// 	properties := c.PostForm("properties")
// 	properties = strings.ReplaceAll(properties, `"`, `\"`) // 转义双引号
// 	// dump to db
// 	music := model.Music{
// 		UUID:       uuid,
// 		Title:      title,
// 		ThumbUrl:   thumbnail,
// 		Properties: properties,
// 	}
// 	println(music.Properties)
// 	println(music.Title)
// 	// 检查数据库中是否已存在记录
// 	var existingMusic model.Music
// 	if err := model.DB.Where("uuid = ?", uuid).First(&existingMusic).Error; err != nil {
// 		if errors.Is(err, gorm.ErrRecordNotFound) {
// 			// 记录不存在，插入新记录
// 			if err := model.DB.Create(&music).Error; err != nil {
// 				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to insert new music record"})
// 				return
// 			}

// 			// 数据库操作成功后，保存文件到本地
// 			musicBlob, err := c.FormFile("musicBlob")
// 			if err != nil {
// 				c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get music file"})
// 				return
// 			}

// 			coverBlob, err := c.FormFile("coverBlob")
// 			if err != nil {
// 				c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get cover file"})
// 				return
// 			}

// 			if err := c.SaveUploadedFile(musicBlob, "objs/music/"+uuid); err != nil {
// 				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save music file"})
// 				return
// 			}

// 			if err := c.SaveUploadedFile(coverBlob, "objs/cover/"+uuid); err != nil {
// 				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save cover file"})
// 				return
// 			}
// 		} else {
// 			// 数据库查询失败（非记录不存在的情况）
// 			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check music record"})
// 			return
// 		}
// 	} else {
// 		// 记录已存在，更新记录
// 		if err := model.DB.Model(&music).Where("uuid = ?", uuid).Updates(&music).Error; err != nil {
// 			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update music metadata"})
// 			return
// 		}
// 	}

// 	c.JSON(http.StatusOK, gin.H{"uuid": uuid})
// }

func MusicExists(c *gin.Context) {
	uuid := c.Query("uuid")
	var music model.Music
	if err := model.GetDB().Where("\"UUID\" = ?", uuid).First(&music).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{"status": false})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": true})
}

func MusicMetaData(c *gin.Context) {
	uuid := c.Query("uuid")
	service := service.NocobaseService{}
	vo, err := service.GetMusicMetaByUUID(uuid)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Failed to get music metadata"})
		return
	}
	c.JSON(http.StatusOK, vo.Into())
}

func MusicAll(c *gin.Context) {
	service := service.NocobaseService{}
	vo_list, err := service.GetMusicMetaByPage()
	println(vo_list)
	// gin.DebugPrintFunc("vo_list", vo_list)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Failed to get music metadata"})
		return
	}
	vo_list_H := make([]gin.H, 0)
	for _, vo := range vo_list {
		vo_list_H = append(vo_list_H, vo.Into())
	}
	c.JSON(http.StatusOK, vo_list_H)
}

func MusicBlob(c *gin.Context) {
	uuid := c.Query("uuid")
	service := service.NocobaseService{}
	filename, err := service.GetMusicBlobByUUID(uuid)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Failed to get music URL"})
		return
	}
	c.File(filename)
}

func MusicCover(c *gin.Context) {
	uuid := c.Query("uuid")
	service := service.NocobaseService{}
	filename, err := service.GetMusicCoverByUUID(uuid)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Failed to get music URL"})
		return
	}
	c.File(filename)
}

// func MusicPresignedUploadURL(c *gin.Context) {
// 	uuidV4 := uuid.New().String()
// 	url, err := service.COSGetPresignedUploadURL(uuidV4)
// 	if err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get presigned upload URL"})
// 		return
// 	}
// 	c.JSON(http.StatusOK, gin.H{"url": url, "uuid": uuidV4})
// }

// func MusicPresignedUploadFinished(c *gin.Context) {
// 	// 获取post payload
// 	var payload struct {
// 		UUID        string `json:"uuid"`
// 		Title       string `json:"title"`
// 		CoverBase64 string `json:"coverBase64"`
// 	}
// 	// 绑定 JSON 到结构体
// 	if err := c.ShouldBindJSON(&payload); err != nil {
// 		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
// 		return
// 	}
// 	// 写入数据库
// 	music := model.Music{
// 		UUID:     payload.UUID,
// 		Name:     payload.Title,
// 		Artist:   "me",
// 		Uploader: "me",
// 		CoverUrl: payload.CoverBase64,
// 	}
// 	if err := model.DB.Create(&music).Error; err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to write to database"})
// 		return
// 	}
// 	c.JSON(http.StatusOK, gin.H{"uuid": payload.UUID})
// }

// func MusicPresignedDownloadURL(c *gin.Context) {
// 	url, err := service.COSGetPresignedDownloadURL("test")
// 	if err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get presigned download URL"})
// 		return
// 	}
// 	c.JSON(http.StatusOK, gin.H{"url": url})
// }

// type Ty_MusicPlaylist_music struct {
// 	UUID     string `json:"uuid"`
// 	Title    string `json:"title"`
// 	Artist   string `json:"artist"`
// 	Uploader string `json:"uploader"`
// 	CoverUrl string `json:"coverUrl"`
// }

// func MusicPlaylist(c *gin.Context) {
// 	uuid := c.Query("uuid")
// 	p := service.PlaylistBuilder(uuid)
// 	musics := p.Musics()

// 	var m = make([]Ty_MusicPlaylist_music, 0)
// 	for _, mm := range musics {
// 		m = append(m, Ty_MusicPlaylist_music{
// 			UUID:     mm.ID(),
// 			Title:    mm.Title(),
// 			Artist:   mm.Artist(),
// 			Uploader: mm.Uploader(),
// 			CoverUrl: mm.CoverUrl(),
// 		})
// 	}
// 	jsonRes := gin.H{
// 		"uuid":       p.ID(),
// 		"title":      p.Title(),
// 		"accessTime": time.Now().Format(time.RFC3339),
// 		"musics":     m,
// 	}

// 	c.JSON(http.StatusOK, jsonRes)
// }

// func MusicGetRandom10(c *gin.Context) {
// 	var m []model.Music
// 	model.DB.Debug().Select("*").Find(&m)

// 	c.JSON(http.StatusOK, m)
// }

// func MusicBlobUrl(c *gin.Context) {
// 	uuid := c.Query("uuid")
// 	m := service.MusicBuilder(uuid)
// 	url, err := m.Url()
// 	if err != nil {
// 		c.JSON(http.StatusNotFound, gin.H{"error": "Failed to get music URL"})
// 		return
// 	}
// 	c.JSON(http.StatusOK, gin.H{"url": url})
// }

// func MusicAddToPlaylist(c *gin.Context) {
// 	var m []model.Music
// 	model.DB.Debug().Select("*").Find(&m)

// 	c.JSON(http.StatusOK, m)
// }
